package com.mspbots.core.wise.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mspbots.core.AbstractBaseController;
import com.mspbots.core.RestServerException;
import com.mspbots.core.wise.model.TenantCompanyWatch;
import com.mspbots.core.wise.service.TenantCompanyWatchService;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Comparator;
import java.util.List;
import java.util.concurrent.Callable;

/**
 * TenScheduleController
 *
 * @author Alex bob(https://github.com/vnobo)
 * @date Created by 2019/6/4
 */
@RestController
@RequestMapping(path = "tenant/company/watch")
public class TenantCompanyWatchController extends AbstractBaseController<TenantCompanyWatch, TenantCompanyWatchService> {

    @PostMapping(path = "insert")
    public Callable insertCompanyWatch(@RequestBody TenantCompanyWatch t) {
        return () -> {
            QueryWrapper<TenantCompanyWatch> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("tenant_id", t.getTenantId())
                    .eq("cw_id", t.getCwId())
                    .eq("enable", true);
            List<TenantCompanyWatch> list = this.service.list(queryWrapper);
            if (!CollectionUtils.isEmpty(list)) {
                throw new CompanyExistsException(500, "The company[" + t.getName() + "] already exists and cannot be added repeatedly!");
            }
            return this.service.save(t);
        };
    }

    @GetMapping(path = "/record")
    public Callable selectRecord(TenantCompanyWatch queryParams) {
        return () -> {
            QueryWrapper<TenantCompanyWatch> queryWrapper = new QueryWrapper<>(queryParams);
            List<TenantCompanyWatch> list = this.service.list(queryWrapper);
            list.sort(Comparator.comparing(TenantCompanyWatch::getId).reversed());
            return list;
        };
    }

    static class CompanyExistsException extends RestServerException {
        public CompanyExistsException(int code, String msg) {
            super(code, msg);
        }
    }
}
